/*
 * basicFunctions.c
 *
 *  Created on: 24/09/2011
 *      Author: utn_so
 */

#include "basicFunctions.h"
#include <stdlib.h>
#include <stdint.h>
#include <string.h>

char wrkDirectory[255];
char logFileName[265];
int32_t LogLevel = 0;

char * ExtractFilePath(const char *path)
{
	char * Result  = (char *)calloc(strlen(path) + 1, sizeof(char));
	char * ptrPath = (char *)calloc(strlen(path) + 1, sizeof(char));
	char * saveptr;
	char * Aux;
	int i = 0;
	int Count = 0;

	strcpy(ptrPath, path);
	Aux = strtok_r(ptrPath, "/", &saveptr);
	while (Aux != NULL) {
		Aux = strtok_r(NULL, "/", &saveptr);
		Count++;
	}

	strcpy(ptrPath, path);
	Aux = strtok_r(ptrPath, "/", &saveptr);
	if(strncmp(path, ".", 1) != 0)
		strcpy(Result, "/");
	for (i = 0; i < Count - 1; i++) {
		Result = strcat(Result, Aux);
		Result = strcat(Result, "/");
		Aux = strtok_r(NULL, "/", &saveptr);
	}

	free(ptrPath);
	return Result;
}

char * ExtractFilename(const char *path)
{
	char * Result;
	char * saveptr;
	char * ptrPath = (char *)calloc(strlen(path) + 1, sizeof(char));
	Result = (char *)calloc(strlen(path) + 1, sizeof(char));

	strcpy(ptrPath, path);
	char * Aux = strtok_r(ptrPath, "/", &saveptr);
	while (Aux != NULL) {
		strcpy(Result, Aux);
		Aux = strtok_r(NULL, "/", &saveptr);
	}

	free(ptrPath);
	return Result;
}

int32_t strpos(const char * str, char delimiter)
{
	int32_t count = 0,
			size = strlen(str);
	while ((str[count] != delimiter) && (count < size)) count++;
	if (count == size)
		return -1;
	return count;
}

void intToStr(int32_t in, char * out)
{
	//Se asume que out es un ptr con mem asignada
	const char desp = '0';
	const int32_t base = 10;
	char digit;
	int32_t cantDigitos = 0;
	int32_t aux = in;

	//Cuenta la cant de digitos del entero
	do {
		aux /= base;
		cantDigitos++;
	} while (aux > 0);

	if (in < 0) //Si el numero es negativo devuelve el modulo
		in *= -1;

	strcpy(out, "");
	out[cantDigitos] = '\0';
	//recorro y asigno los digitos desde el de menor peso al de mayor
	while (cantDigitos > 0) {
		digit = (in % base) + desp;
		out[cantDigitos - 1] = digit;
		in /= base;
		cantDigitos--;
	}
}

void setWorkingDirectory(const char * path)
{
	char * aux = ExtractFilePath(path);
	strcpy(wrkDirectory, aux);
	free(aux);
}

void getWorkingDirectory(char * Result)
{
	strcpy(Result, wrkDirectory);
}

void setLogFileName(const char * name)
{
	strcpy(logFileName, wrkDirectory);
	strcat(logFileName, name);
}

char * getLogFileName()
{
	return logFileName;
}

void setLogLevel(int32_t aLogLevel)
{
	LogLevel = aLogLevel;
}

int32_t getLogLevel()
{
	return LogLevel;
}


int32_t power(int32_t base, int32_t exp)
{
	if(exp == 0) return 1;
	return base * power(base, exp - 1);
}
